<?php
/**
 * 本程序由恩赋科技提供
 * www.enfukeji.com
 * QQ291624720
 */
defined('IN_IA') or exit('Access Denied');
define("DAKA_PATH", '/addons/dashen_zaoqizhuanqian/');
define("IMG_DAKA_PATH", '../addons/dashen_zaoqizhuanqian/');
define("MODULE_NAME", 'dashen_zaoqizhuanqian');
include_once "wxBizDataCrypt.php";
class dashen_zaoqizhuanqianModuleWxapp extends WeModuleWxapp {
	function __construct() {
        global $_W,$_GPC;
        $setting = pdo_fetch('SELECT * FROM ' . tablename('zdaka_config') . ' WHERE uniacid ='.$_W['uniacid']);
		$this->getopenidinfo();
        $others =json_decode($setting['other_setting'],true);
       // $other =json_decode($setting['other_setting'],true);
        $set =json_decode($setting['settings'],true);
        $endtime   =  !empty($set['endtime'])?$set['endtime']:8;
        $today = date('Y-m-d',time());
        $zhouqi1=!empty($others['zhouqi'])?intval($others['zhouqi']):21;
		$zhouqi1 =  $zhouqi1>0?$zhouqi1-1:0;
        $xuni=!empty($others['xuni'])?$others['xuni']:'0,0,10';
        $xuni1=explode(',',$xuni);
        $this->xnumber=$xuni1[0];
        $this->xmoney=$xuni1[1];
        $this->xbili=$xuni1[2];
        $this->today_end = strtotime($today)+3600*$endtime;
        $this->zhouqi =$zhouqi1;
        $this->bili =$set['bili'];
        $this->personNum =$set['personNum']?$set['personNum']:0;
        $this->invitation_endtime =$set['invitation_endtime']?$set['invitation_endtime']:7;
        $this->invitation_money =$set['invitation_money']?$set['invitation_money']:0;
        $this->txsx =!empty($set['txsx'])?$set['txsx']:0;
        $this->fdje =!empty($set['fdje'])?$set['fdje']:0;
        $this->wenzi =$others['wenzi'];
        $this->zstate =$set['zstate'];
        $this->fstate =!empty($set['fstate'])?$set['fstate']:0;
        $this->djstate =!empty($set['djstate'])?$set['djstate']:0;
        $this->ysstate =!empty($set['ysstate'])?$set['ysstate']:0;
        $this->tzstate =!empty($set['tzstate'])?$set['tzstate']:0;
        $this->txdemo =!empty($set['txdemo'])?$set['txdemo']:'请输入支付宝账号';
        $this->txbank =!empty($set['txbank'])?$set['txbank']:'后台未设置';
        $this->paychecked =!empty($set['paychecked'])?$set['paychecked']:0;
        $this->biz_id =$set['biz_id'];
        $service=!empty($set['service'])?$set['service']:0;
        $this->service =$service;
        $this->dk_endtime = !empty($set['endtime'])?$set['endtime']:8;
        $this->zd_tx = $others['tixian'];
        $this->zd_yj = $others['yajin'];
        $this->uniacid = $_W['uniacid'];
        $this->openid = $_W['fans']['openid'];
        $this->title = $set['titles'];
        $this->config =$setting;
    }
	public function doPageSystem(){
		global $_W, $_GPC;
		$res=pdo_get('zdaka_config',array('uniacid'=>$_W['uniacid']));
		$set = json_decode($res['settings'],true);
		$other = json_decode($res['other_setting'],true);
		
		$res1['set']['rule'] =htmlspecialchars_decode($other['wenben']);
		$res1['set']['bank']=explode(",",$set['txbank']);
		$res1['set']['num']=$other['num'];
        $res1['set']['paychecked'] =!empty($set['paychecked'])?$set['paychecked']:0;
		echo json_encode($res1);
	}
	//获取openid
	public function doPageOpenid(){
		global $_W, $_GPC;
		$res=pdo_get('zdaka_config',array('uniacid'=>$_W['uniacid']));
		$res['settings'] = json_decode($res['settings'],true);
		$code=$_GPC['code'];
		$appid=$res['settings']['appid'];
		$secret=$res['settings']['appsecret'];

	// echo $appid;die;
		$url="https://api.weixin.qq.com/sns/jscode2session?appid=".$appid."&secret=".$secret."&js_code=".$code."&grant_type=authorization_code";
			
		function httpRequest($url,$data = null){
			$curl = curl_init();
			curl_setopt($curl, CURLOPT_URL, $url);
			curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
			curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
			if (!empty($data)){
				curl_setopt($curl, CURLOPT_POST, 1);
				curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
			}
			curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		//执行
			$output = curl_exec($curl);
			curl_close($curl);
			return $output;
		}
		$res=httpRequest($url);
		print_r($res);
	}
	//登录用户信息
	public function doPageLogin(){
		global $_GPC, $_W;
		$openid=$_GPC['openid'];
		if($_GPC['openid'] == 'undefined'){
			echo json_encode(0);
			exit();
		}
		$res=pdo_get('zdaka_user',array('openid'=>$openid,'uniacid'=>$_W['uniacid']));
		if($res){
			$user_id=$res['id'];
			if($_GPC['headimgurl']){
				$data['headimgurl']=$_GPC['headimgurl'];
			}
			if($_GPC['nickname']){
				$data['nickname']=$_GPC['nickname'];
			}
			if($_GPC['openid']){
				$data['openid']=$_GPC['openid'];
			}
			$res = pdo_update('zdaka_user', $data, array('id' =>$user_id));
			$user=pdo_get('zdaka_user',array('openid'=>$openid,'uniacid'=>$_W['uniacid']));
			echo json_encode($user);
		}else{
			$data['openid']=$_GPC['openid'];
			$data['uid']=$_W['uid'];
			$data['headimgurl']=$_GPC['headimgurl'];
			$data['nickname']=$_GPC['nickname'];
			$data['uniacid']=$_W['uniacid'];
			$data['reg_time']=date('Y-m-d H:i:s',time());
			
			$res2=pdo_insert('zdaka_user',$data);
			$user=pdo_get('zdaka_user',array('openid'=>$openid,'uniacid'=>$_W['uniacid']));
			echo json_encode($user);
		}
	}
	    //通过用户id请求用户信息
    public function doPageUserInfo() {
        global $_W, $_GPC;
		$openid=$_GPC['openid'];
        $res = pdo_get('zdaka_user', array('openid' => $_GPC['openid']));
        echo json_encode($res);
    }
	public function doPageIndex() {
        // $this->CreateImage('13213');exit;
        //这个操作被定义用来呈现 功能封面
        //前台页面
        global $_W,$_GPC;
      
        //var_dump($fid);exit;
        $follow_satus = 1;
        $uniacid =  $_W['uniacid'];
		$openid=$_GPC['openid'];
		$fid=$_GPC['fid'];
        $time = date('Y-m-d H:i:s',time());
        $today = date('Y-m-d',time());
        $tomorrow = date("Y-m-d",strtotime("+1 day"));
        $yesterday = date("Y-m-d",strtotime("-1 day"));
        $user = pdo_fetch('SELECT * FROM ' . tablename('zdaka_user') . ' WHERE uniacid ='.$uniacid. ' AND openid ="' .$openid.'"');
        if($user['state']==1){
            message('你的数据异常请联系平台客户！', '', 'error');exit;
       }
        //读取设置开始时间和结束时间
        $setting = pdo_fetch('SELECT * FROM ' . tablename('zdaka_config') . ' WHERE uniacid ='.$uniacid);
        $set =json_decode($setting['settings'],true);
        $starttime =  !empty($set['starttime'])?$set['starttime']:0;
        $endtime =  !empty($set['endtime'])?$set['endtime']:8;
		$a=explode('.',$starttime);
        $b=$a[0].':'.($starttime-$a[0])*60;
        if($a[1]==0){
         $b=$a[0].':'.'00';
        }
		$c=explode('.',$endtime);
		$d=$c[0].':'.($endtime-$c[0])*60;
		 if($c[1]==0){
         $d=$c[0].':'.'00';
        }
		$data['end_time'] = $c[0];
		$data['end_branch'] = ($endtime-$c[0])*60;
		$data['starttime'] = $b;
		
		$data['endtime'] = $d;
        $other =json_decode($setting['other_setting'],true);
		$data['other']['yajins']=explode(",",$other['yajin']);
		$data['other']['zyajins']=explode(",",$other['zyajin']?$other['zyajin']:$other['yajin']);
        $data['other']['images']=$other['images']?explode(",",$other['images']):"";
        $data['setting']['share'] =json_decode($setting['share_setting'],true);
		$data['setting']['set'] = array();
        $today_5 = strtotime($today)+3600*$starttime;
        $today_8 = strtotime($today)+3600*$endtime;
        $djs=0;
        if(strtotime($time)<=$today_5){
            $djs=$today_5-time();
        }
        if(strtotime($time)>=$today_8){
            $djs= $today_5+86400-time();
        }
        $upstate=pdo_getall('zdaka_yajin_record',array('uniacid'=>$uniacid,'yajin_state'=>1));
        foreach ($upstate as $k=>$v){
            if( strtotime($upstate[$k]['apply_data'])<strtotime($today)){
                pdo_update('zdaka_yajin_record',array('yajin_state'=>0,'demo'=>'未打卡'),array('id'=>$v['id']));
            }
        }
        // 判断押金是否可用
        $is_tiao='0';
        $yajin = pdo_fetch('SELECT * FROM ' . tablename('zdaka_yajin_record') . ' WHERE  uniacid ='.$uniacid. ' AND openid ="' .$openid .'" and yajin_state= 1');
        if(!empty($yajin)){
            $is_tiao='1';
        }else{
            $is_tiao='0';
        }
		
		if(strtotime($time)>=$today_8){
			$is_tiao = '2';
		}
        //if($this->fstate==1){
          //  if(strtotime($time)>$today_8){
            //    $file_name = MODULE_ROOT.'/'.$_W['uniacid'].'/record/'.$today.'.rlc';
              //  if(!file_exists($file_name)){
                //    $is_tiao='4';
  //              }
//
    //        }
      //  }
        //查询可用押金数量
        //if(strtotime($time)<$today_8){
        //    $yajin_list =  pdo_fetchall('SELECT * FROM '. tablename('zdaka_yajin_record').' WHERE apply_data="'.$today.'" AND  uniacid ='.$uniacid.'  AND yajin_state=1 order by  yajin_data desc');
        //}else{
            $yajin_list =  pdo_fetchall('SELECT * FROM '. tablename('zdaka_yajin_record').' WHERE apply_data="'.$today.'" AND  uniacid ='.$uniacid.'  AND yajin_state=1 order by yajin_data desc ');
        //}
        $total_money=0;
        foreach ($yajin_list as $k=>$v){
            $total_money+= $v['yajin_money'];
        }
        //查询昨天记步成功和失败数量
        if(strtotime($time)>$today_8){
           // pdo_update('zdaka_yajin_record',array('Invaliddate' => $today),array('uniacid' => $uniacid,'yajin_state' => 1,'daka_date !=' => $today,'apply_data <'=>date('Y-m-d H:i:s',$today_8)));
            $success_total = pdo_fetchcolumn('SELECT COUNT(id) FROM '. tablename('zdaka_sign_record').' WHERE uniacid ='.$uniacid.' AND daka_date ="'.$yesterday.'"');//成功人数
            $fail_total =  pdo_fetchcolumn('SELECT COUNT(id) FROM '. tablename('zdaka_yajin_record').' WHERE uniacid ='.$uniacid.' AND Invaliddate ="'.$yesterday.'"');//失败人数

        }else{

            $success_total = pdo_fetchcolumn('SELECT COUNT(id) FROM '. tablename('zdaka_sign_record').' WHERE uniacid ='.$uniacid.' AND daka_date ="'.$yesterday.'"');//成功人数
            $fail_total =  pdo_fetchcolumn('SELECT COUNT(id) FROM '. tablename('zdaka_yajin_record').' WHERE uniacid ='.$uniacid.' AND Invaliddate ="'.$yesterday.'"');//失败人数
        }
		
		$data['total_money'] = $total_money;
	
        //查询昨日运动达人
       // if(strtotime($time)>$today_8){
       //     $data['zqzx'] = pdo_fetch('SELECT * FROM '. tablename('zdaka_sign_record').' WHERE uniacid ='.$uniacid.' AND daka_date ="'.$today.'" order by daka_datatime  limit 1');//成功人数
       // }else{
            $data['zqzx'] = pdo_fetch('SELECT * FROM '. tablename('zdaka_sign_record').' WHERE uniacid ='.$uniacid.' AND daka_date ="'.$yesterday.'" order by num desc  limit 1');//成功人数
       // }
        //查询毅力之星
		$data['ylzx'] = pdo_fetch('SELECT * FROM ' . tablename('zdaka_yajin_record') . ' WHERE uniacid ='.$uniacid. ' AND yajin_state = 1  order by yajin_data  limit 1' );
         if($data['ylzx']){
			$data['ylzx']['sss'] = intval((strtotime($time)-strtotime(date('Y-m-d',strtotime($data['ylzx']['yajin_data']))))/86400)."天";
		 }
		 
        //$data['ylzx'] = pdo_fetch('SELECT * FROM '. tablename('zdaka_total_record').' WHERE uniacid ='.$uniacid.' AND  last_sign_date="'.$yesterday.'" order by user_total_score desc  ,last_sign_time asc limit 1');

        //查询手气之星
		$data['sqzx'] = pdo_fetch('SELECT * FROM ' . tablename('zdaka_grant_record') . ' WHERE uniacid ='.$uniacid. ' AND grant_date ="' .$yesterday .'" order by grant_money desc limit 1');
       // $data['sqzx'] = pdo_fetch('SELECT * FROM '. tablename('zdaka_total_record').' WHERE uniacid ='.$uniacid.' AND  last_sign_date="'.$yesterday.'" order by user_total_money desc  ,last_sign_time asc limit 1');

        //超过打卡时间访问页面执行打卡金发放
		//@TODO
  	
		$data['yajin_list'] = $yajin_list;
		$data['is_tiao'] = $is_tiao;
        $data['nostate']   =  !empty($set['nostate'])?$set['nostate']:0;
        $data['notice']=pdo_fetchall('SELECT * FROM '. tablename('zdaka_notice_record').' WHERE acid ='.$uniacid.'  and state=0 ');
        $data['blist']=pdo_fetchall('SELECT * FROM '. tablename('zdaka_list').' WHERE acid ='.$uniacid.'  order by xuhao limit 0,4 ');
        $data['daymoney']=pdo_get('zdaka_daymoney_record',array('acid'=>$uniacid,'date'=>$tomorrow));
		
	
		$data['success_total'] =$success_total+(int)($this->xnumber*$this->xbili/10);
		$data['fail_total'] = $fail_total;
		if($data['daymoney']){ //总金额
			$data['total_money'] = $total_money+$this->xmoney+$data['daymoney'];
		}else{
			$data['total_money'] = $total_money+$this->xmoney;
		}
		$data['personNum'] = count($data['yajin_list'])+$this->xnumber; //参与人数
		
       echo json_encode($data);
    }
	
	public function doPagejibuInfo(){
		global $_GPC, $_W;
		$openid=$_GPC['openid'];
		$uniacid = $this->uniacid;
        $data['userInfo'] = pdo_get('zdaka_user', array('openid' => $_GPC['openid']));
		$data['yajin'] = pdo_fetch('SELECT * FROM ' . tablename('zdaka_yajin_record') . ' WHERE yajin_state=1 AND uniacid ='.$uniacid. ' AND openid ="' .$openid .'"  order by yajin_data,id desc limit 1');

        $data['total_day'] = pdo_fetchcolumn('SELECT COUNT(id) FROM ' . tablename('zdaka_sign_record') . ' WHERE uniacid ='.$this->uniacid. ' AND openid ="'.$openid.'"');
		echo json_encode($data);
	}
	
	 public function doPageTixian(){
        //提现
        global $_W,$_GPC;
        $uniacid = $this->uniacid;
        $time = strtotime(date('Y-m-d H:i:s'));
		$openid = $_GPC['openid'] ? $_GPC['openid'] : '';
        $user = pdo_fetch('SELECT * FROM ' . tablename('zdaka_user') . ' WHERE uniacid ='.$this->uniacid. ' AND openid ="' .$openid.'"');
		$countUser = pdo_fetchcolumn('SELECT count(id) FROM ' . tablename('zdaka_user') . ' WHERE uniacid ='.$this->uniacid. ' AND fuid ="' .$user['id'].'"');
		if($this->personNum>0 && $countUser<$this->personNum)
		{
			echo json_encode(array('status'=>0,'msg'=>'你的账号还需邀请'.($this->personNum-$countUser).'个好友'));
            exit;
		}
		if($user['money']<=0){
			echo json_encode(array('status'=>0,'msg'=>'你的可用余额为0，不能提现'));
            exit;
        }
        if($user['money'] < $this->zd_tx){
			echo json_encode(array('status'=>0,'msg'=>'提现金额不能少于'.$this->zd_tx.'元！'));
            exit;
        }
        $data = array(
            'uniacid' => $user['uniacid'],
            'uid' =>$user['id'],
            'openid' => $user['openid'],
            'headimgurl' =>$user['headimgurl'],
            'nickname' => $user['nickname'],
            'tixian_data' =>date('Y-m-d H:i:s',time()),
            'tixian_money' => $user['money']*(100-$this->txsx)/100,
            'ymoney'=>$user['money'],
            'zhanghao' => $_GPC['zhanghao'],
            'type' => $_GPC['pay_type'],
            'name' => $_GPC['name'],
            'bank'=>$_GPC['bank'],
            'kbank'=>$_GPC['kbank'],
            'tixian_state' =>0
        );
        $res= pdo_insert('zdaka_tixian_record', $data);

        if($res){
            pdo_update('zdaka_user', array('money ' =>0),array('id' => $user['id']));
			echo json_encode(array('status'=>1,'msg'=>'申请成功'));
            exit;
        }else{
			echo json_encode(array('status'=>0,'msg'=>'申请失败'));
            exit;
        }

    }
	
	public function doPageJrmx() {
        //这个操作被定义用来呈现 微站快捷功能导航
        //好友列表
        global $_W,$_GPC;
		
        $uid = $_GPC['uid'];
        $uniacid =  $_W[uniacid];
        $nickname = $_W['fans']['nickname'];
        $time = date('Y-m-d H:i:s',time());
        $today = date('Y-m-d',time());
        $yesterday = date("Y-m-d",strtotime("-1 day"));
        $value = trim($_GPC['type']);
        $array = array();
        if($value=='Luck'){
            $rank_record = pdo_fetchall('SELECT * FROM ' . tablename('zdaka_grant_record') . ' WHERE uniacid ='.$uniacid. ' AND grant_date ="' .$yesterday .'" order by grant_money desc limit 0, 10');
            foreach($rank_record as $k=>$item){
                $rank_record[$k]['sss'] =$item['grant_money'];
            }
            echo json_encode($rank_record);
            exit;
        }
        if($value=='Morning'){
            $rank_record = pdo_fetchall('SELECT * FROM ' . tablename('zdaka_sign_record') . ' WHERE uniacid ='.$uniacid. ' AND daka_date ="' .$yesterday .'"  order by num desc   limit 0, 10'  );
            foreach($rank_record as $k=>$item){
                $rank_record[$k]['sss'] ="步数".$item['num'];
            }
            echo json_encode($rank_record);
            exit;
        }
        if($value=='Will'){
            $rank_record = pdo_fetchall('SELECT * FROM ' . tablename('zdaka_yajin_record') . ' WHERE uniacid ='.$uniacid. ' AND yajin_state = 1  order by yajin_data  limit 0, 10' );
            foreach($rank_record as $k=>$item){
                $rank_record[$k]['sss'] =intval((strtotime($time)-strtotime(date('Y-m-d',strtotime($item['yajin_data']))))/86400)."天";
            }
            echo json_encode($rank_record);
            exit;
        }
    }
	//邀请信息
	public function doPageYqhy() {
        global $_W,$_GPC;
		$openid = $_GPC['openid'];
		$user = pdo_fetch('SELECT * FROM ' . tablename('zdaka_user') . ' WHERE uniacid ='.$this->uniacid. ' AND openid ="' .$openid.'"');
        $uid = $user['id'];
        $uniacid =  $this->uniacid;
        $acid=$this->uniacid;
        $zuijing = pdo_fetch('SELECT * FROM ' . tablename('zdaka_user') . ' WHERE uniacid ='.$uniacid. ' AND fuid =' .$uid.' order by reg_time desc limit 0, 1' );
        $zuiduo = pdo_fetch('SELECT sum(money) as money ,zuid FROM ' . tablename('zdaka_yqsy_record') . ' WHERE fuid ='.$uid.' group by zuid order by sum(money) desc limit 0, 1 ' );
        $zuiduo1=pdo_get('zdaka_user',array('id'=>$zuiduo['zuid']));
        $cishu = pdo_fetch('SELECT count(id) as cishu ,zuid FROM ' . tablename('zdaka_yqsy_record') . ' WHERE fuid ='.$uid.' group by zuid order by count(id) desc limit 0, 1 ' );
        $cishu1=pdo_get('zdaka_user',array('id'=>$cishu['zuid']));
        $blist=pdo_fetchall('SELECT * FROM '. tablename('zdaka_list').' WHERE acid ='.$uniacid.'  order by xuhao limit 0,4 ');
		$num = pdo_fetchcolumn('SELECT count(id) FROM ' . tablename('zdaka_user') . ' WHERE uniacid ='.$uniacid. ' AND fuid =' .$uid);
          echo json_encode(array('zuijing'=>$zuijing,'zuiduo'=>$zuiduo,'zuiduo1'=>$zuiduo1,'cishu'=>$cishu,'cishu1'=>$cishu1,'blist'=>$blist,'num'=>$num?$num:0));
            exit;
    }
	//type邀请信息
	 public function doPageYqlb() {
        //这个操作被定义用来呈现 微站快捷功能导航
        //好友列表
        global $_W,$_GPC;
		$openid = $_GPC['openid'];
		$user = pdo_fetch('SELECT * FROM ' . tablename('zdaka_user') . ' WHERE uniacid ='.$this->uniacid. ' AND openid ="' .$openid.'"');
        $uid = $user['id'];
		$uniacid =  $this->uniacid;
        $nickname = $user['nickname'];
        $time = date('Y-m-d H:i:s',time());
        $today = date('Y-m-d',time());
        $value = trim($_GPC['type']);
        $array = array();
        if($value=='lb'){
            $rank_record = pdo_fetchall('SELECT * FROM ' . tablename('zdaka_user') . ' WHERE uniacid ='.$uniacid. ' AND fuid =' .$uid .' order by reg_time desc ');
            foreach($rank_record as $k=>$item){
                $rank_record[$k]['nickname'] =  mb_substr($item['nickname'], 0, 12,'utf-8');
                $rank_record[$k]['info'] =   date('Y-m-d',strtotime($item['reg_time']));

            }
            echo json_encode($rank_record);
            exit;
        }
        if($value=='money'){
            $rank_record = pdo_fetchall('SELECT sum(money) as money ,zuid FROM ' . tablename('zdaka_yqsy_record') . ' WHERE fuid ='.$uid.' group by zuid ' .' order by sum(money) desc limit 0, 40'  );
            foreach($rank_record as $k=>$item){
                $rank_record[$k]['money'] = round($item['money'],2);
                $rank_record[$k]['user'] = pdo_get('zdaka_user',array('id'=>$item['zuid']));
				$rank_record[$k]['nickname'] =  mb_substr( $rank_record[$k]['user']['nickname'], 0, 12,'utf-8');
				$rank_record[$k]['headimgurl'] =  $rank_record[$k]['user']['headimgurl'];
				$rank_record[$k]['date'] = date('m-d H:s',strtotime($item['date']));
				$rank_record[$k]['info'] =  '分润'.$rank_record[$k]['money'];
            }
            echo json_encode($rank_record);
            exit;
        }
        if($value=='mx'){
            $rank_record = pdo_fetchall('SELECT * FROM ' . tablename('zdaka_yaoqing_record') . ' WHERE uniacid ='.$uniacid. ' AND invitation_money>0 AND invitation_status=1  AND fuid =' .$uid .' order by invitation_time desc limit 0, 40' );
            foreach($rank_record as $k=>$item){
                $rank_record[$k]['user'] = pdo_get('zdaka_user',array('id'=>$item['cuid']));
				$rank_record[$k]['nickname'] =  mb_substr( $rank_record[$k]['user']['nickname'], 0, 12,'utf-8');
				$rank_record[$k]['headimgurl'] =  $rank_record[$k]['user']['headimgurl'];
                $rank_record[$k]['date'] = date('Y-m-d',strtotime($item['invitation_time']));
				$rank_record[$k]['info'] = '奖励'.$rank_record[$k]['invitation_money'];
            }
            echo json_encode($rank_record);
            exit;
        }
    }
	//个人中心信息
	 public function doPageRecord() {
        ////这个操作被定义用来呈现 微站快捷功能导航
        //提现记录
        global $_W,$_GPC;
        $openid = $_GPC['openid'];
        $uniacid =  $this->uniacid;
		$type = trim($_GPC['type']);
		$pageindex = max(1, intval($_GPC['page']));
		$pagesize=$_GPC['pagesize'];
        $array = array();
        if($type=='tixian'){
			$rank_record = pdo_fetchall('SELECT * FROM ' . tablename('zdaka_tixian_record') . ' WHERE uniacid ='.$uniacid. ' AND openid ="' .$openid. '" order by tixian_data desc LIMIT ' .($pageindex - 1) * $pagesize.",".$pagesize);
			foreach($rank_record as $key => $val){
			
				$rank_record[$key]['t2'] = $val['tixian_data'].'提现'.$val['tixian_money'];
				 if ($val['tixian_state']=='1'){
					 $rank_record[$key]['t3'] = '提现已到账';
				 }else if( $val['tixian_state']=='2' ){
					 $rank_record[$key]['t3'] = $val['demo'];
				 }else{
					 $rank_record[$key]['t3'] = '提现待审核';
				 }
			}
			echo json_encode($rank_record);
            exit;
		}
		
		if($type=='zhanji'){
			$sign_record = pdo_fetchall('SELECT * FROM ' . tablename('zdaka_sign_record') . ' WHERE uniacid ='.$uniacid. ' AND openid ="' .$openid. '" order by daka_datatime desc LIMIT ' .($pageindex - 1) * $pagesize.",".$pagesize);
			foreach($sign_record as $key=>$val){
				$sign_record[$key]['t2'] = '步数：'.$val['num'];
				$sign_record[$key]['t3'] = '奖金状态：'.$val['state']=='1'?'未发放':'已发放';
			}
			echo json_encode($sign_record);
            exit;
		}
		if($type=='jiangli'){
			$bonus_record = pdo_fetchall('SELECT * FROM ' . tablename('zdaka_grant_record') . ' WHERE uniacid ='.$uniacid. ' AND openid ="' .$openid. '" order by grant_data desc LIMIT ' .($pageindex - 1) * $pagesize.",".$pagesize);
			foreach($bonus_record as $key=>$val){
				$bonus_record[$key]['t2'] = $val['demo'];
				$bonus_record[$key]['t3'] = '共获取：'.$val['bonus_num'].'份 共'.$val['grant_money'];
			}
			echo json_encode($bonus_record);
            exit;
		}
		if($type=='tiaozhan'){
			$pay_record = pdo_fetchall('SELECT * FROM ' . tablename('zdaka_yajin_record') . ' WHERE uniacid ='.$uniacid. ' AND openid ="' .$openid. '" order by yajin_data desc LIMIT ' .($pageindex - 1) * $pagesize.",".$pagesize);
			foreach($pay_record as $key=>$val){
				$pay_record[$key]['t2'] = date('Y-m-d',strtotime($val['yajin_data'])).'缴纳挑战金'.$val['yajin_money'];
				$pay_record[$key]['t3'] = '挑战金状态'.$val['yajin_state']=='1'?'可用':'不可用。原因'.$val['demo'];
			}
			echo json_encode($pay_record);
            exit;
		}
        echo json_encode(array());
            exit;
    }
	//几步参数更新
    public function doPageSign() {
        //这个操作被定义用来呈现 微站快捷功能导航
        //打卡
        global $_W,$_GPC;
       $openid = $_GPC['openid'];
       $num = $_GPC['num'];//当前记步数据
		$user = pdo_fetch('SELECT * FROM ' . tablename('zdaka_user') . ' WHERE uniacid ='.$this->uniacid. ' AND openid ="' .$openid.'"');
        $uid = $user['id'];
        $uniacid =  $this->uniacid;
     
        $headimgurl =  $user['headimgurl']; //头像
        $nickname = $user['nickname'];
        $time = date('Y-m-d H:i:s',time());
        $today = date('Y-m-d',time());
        $yesterday = date("Y-m-d",strtotime("-1 day"));
        //判断是是否存在可用打卡押金
        $yajin = pdo_fetch('SELECT * FROM ' . tablename('zdaka_yajin_record') . ' WHERE uniacid ='.$uniacid. ' AND apply_data ="' .$today .'" AND openid ="' .$openid .'"  and yajin_state = 1');
	
	   if(empty($yajin)){
            $row['Msg']='未交保证金';
            $row = json_encode($row);
            echo $row;
            exit;
        }
        //读取设置达成记步总数
        $setting = pdo_fetch('SELECT * FROM ' . tablename('zdaka_config') . ' WHERE uniacid ='.$uniacid);
		
        $set =json_decode($setting['settings'],true);
        $other =json_decode($setting['other_setting'],true);
        $starttime =  !empty($set['starttime'])?$set['starttime']:0;
        $endtime   =  !empty($set['endtime'])?$set['endtime']:23;
        $today_5 = strtotime($today)+3600*$starttime;
        $today_8 = strtotime($today)+3600*$endtime;
        //查询是今天否完成记步，如果没有记步，执行记步，如果有记步。更新记步数据
		
		if($num<$other['num']){
			$row['Msg']='当前记步没完成。不能打卡';
			$row['State']=202;
            $row = json_encode($row);
            echo $row;
            exit;
		}

        $sql = 'SELECT *  FROM ' . tablename('zdaka_sign_record') . ' WHERE uniacid ='.$uniacid. ' AND openid ="' .$openid. '" AND daka_date = "'.$today.'"';
        $qian = pdo_fetch($sql);
        if($qian){
			 $post = array(
                'num' => $num,
               'jibu_status'=>1,
                'jibu_uptime' =>  $time
            );
            pdo_update('zdaka_sign_record',$post,array('id'=>$qian['id'],'openid'=>$openid));
        }else if(strtotime($time)>=$today_5 && strtotime($time)<=$today_8){
            //插入打卡记录
            $post = array(
                'uniacid' => $this->uniacid,
                'uid' =>  $user['id'],
                'openid' => $user['openid'],
                'nickname' => $user['nickname'],
                'headimgurl' =>$user['headimgurl'],
                'daka_date' => $today,
                'daka_datatime' => $time,
                'huikuan_date' => $yajin['huikuan_date'],
                'bonus_num' => $yajin['yajin_money'],
                'yid' => $yajin['id'],
				'num' => $num,
              	'jibu_status'=>1,
                'jibu_time' =>  $time
            );
            pdo_insert('zdaka_sign_record', $post);
            //更改押金表中记步状态为已完成
            pdo_update('zdaka_yajin_record',array('is_daka' => 1,'daka_date'=>$today),array('uniacid' => $uniacid,'yajin_state' => 1,'openid'=>$openid));

            //查询记录天数表中是否有记录
            $sql = 'SELECT *  FROM ' . tablename('zdaka_total_record') . ' WHERE uniacid ='.$uniacid. ' AND openid ="' .$openid.'"';
            $rel  = pdo_fetchall($sql);
            if($rel){
                //查询昨天是否记步完成，如果成功填上累加，如果没成功，记步天数从新计算
                $sql1 = 'SELECT *  FROM ' . tablename('zdaka_total_record') . ' WHERE uniacid ='.$uniacid. ' AND openid ="' .$openid. '" AND last_sign_date = "'.$today.'"';
                $result = pdo_fetchall($sql1);
                if($result){
                    $data = array(
                        'uniacid' => $this->uniacid,
                        'uid' =>  $user['id'],
						'openid' => $user['openid'],
						'nickname' => $user['nickname'],
						'headimgurl' =>$user['headimgurl'],
                        'last_sign_date' => $today,
                        'last_sign_time' => $time,
                        'user_total_score' => $result['0']['user_total_score']+1,
                    );
                    pdo_update('zdaka_total_record', $data,array('uniacid' => $this->uniacid, 'openid' => $this->openid));
                }
                else{
                    $data = array(
                        'uniacid' => $this->uniacid,
						'uid' =>  $user['id'],
						'openid' => $user['openid'],
						'nickname' => $user['nickname'],
						'headimgurl' =>$user['headimgurl'],
                        'last_sign_date' => $today,
                        'last_sign_time' => $time,
                        'user_total_score' => 1,
                    );
                    pdo_update('zdaka_total_record', $data,array('uniacid' => $this->uniacid, 'openid' => $this->openid));
                }
            }
            else{
                $data = array(
                    'uniacid' => $this->uniacid,
                    'uid' =>  $user['id'],
					'openid' => $user['openid'],
					'nickname' => $user['nickname'],
					'headimgurl' =>$user['headimgurl'],
                    'last_sign_date' => $today,
                    'last_sign_time' => $time,
                    'user_total_score' =>1,
                );
                pdo_insert('zdaka_total_record', $data);
            }
            $row['State'] = 200;
            $row['Msg']='记步成功！';
            $row = json_encode($row);
            echo $row;
        }else{
            $yajin = pdo_fetch('SELECT * FROM ' . tablename('zdaka_yajin_record') . ' WHERE uniacid ='.$uniacid. ' AND apply_data ="' .$today .'" AND openid ="' .$this->openid .'"  order by yajin_data,id desc limit 1');
            pdo_update('zdaka_yajin_record', array('yajin_state' =>0,'demo'=>$today.'记步失败'),array('id'=>$yajin['id']));

            $row['State'] = 202;
            $row['Msg']='打卡步数不达标';
            $row = json_encode($row);
            echo $row;
        }
    }



	  //绑定邀请人
    public function doPageBinding() {
        global $_W, $_GPC;
      
      echo 'a';
    }

	public function doPageCreateOrder() {
        global $_W, $_GPC;
		require IA_ROOT . '/addons/dashen_zaoqizhuanqian/extends/weixin.class.php';
		$object = new weixin($_W['other_setting']['settings']);
        $uniacid = $this->uniacid;

      	$openid =  $_W['member']['openid'];
      	if(empty($_GPC['isTiao'])){
          	$ttoday =  date('Y-m-d',time());
        	$payInfo = pdo_fetch('SELECT * FROM ' . tablename('zdaka_pay_record') . ' WHERE uniacid ='.$uniacid. ' AND state=1 AND zstate=0 AND   time >="' .$ttoday .'" AND openid ="' .$openid .'"  limit 1');
          	if($payInfo){
            	exit(json_encode( array("status" => 0 , 'msg'=>'你今天已经支付挑战！请去追加挑战')));
            }
          
        }
        //构造支付请求中的参数
        $time = date('Y-m-d H:i:s',time());
		$yajin = explode("," , $_W['other_setting']['other_setting']['yajin'] );
        $params = array(
            'tid' => $uid.time(),      //充值模块中的订单号，此号码用于业务模块中区分订单，交易的识别码
            'ordersn' => $uid.time(),  //收银台中显示的订单号
            'title' => '挑战金',          //收银台中显示的标题
            'fee' => $yajin[$_GPC['price_id']>=0?$_GPC['price_id']:0],      //收银台中显示需要支付的金额,只能大于 0
            'user' => $_W['member']['id'],     //付款用户, 付款的用户名(选填项)
            'openid' => $_W['member']['openid'],
            'serial' => time() . rand(0000, 9999) + $uid,
            'state' => 0,
            'zstate' => $_GPC['isTiao'],
            'uniacid' => $this->uniacid,
            'time'=>$time
        );
		$res = pdo_insert('zdaka_pay_record', $params);
		$result = $object->pay_mobile( $params );
		exit(json_encode( array("status" => 1 , 'data' => array("pay_info" => $result , 'order_info' => $params))));
	}
	
	private function getopenidinfo() {
		global $_W, $_GPC;
		$openid = $_GPC['openid'] ? $_GPC['openid'] : '';
		if( $openid ) {
			$data = pdo_fetch("SELECT * FROM " . tablename("zdaka_user") . " WHERE `openid` = :openid" , array("openid" => $openid));
			if( $data ) {
				$setting = pdo_fetch('SELECT * FROM ' . tablename('zdaka_config') . ' WHERE uniacid ='.$_W['uniacid']);
				$setting['settings'] = $setting['settings'] ? json_decode( $setting['settings'] , true ) : '';
				$setting['other_setting'] = $setting['other_setting'] ? json_decode( $setting['other_setting'] , true ) : '';
				$_W['openid'] = $openid;
				$_W['member'] = $data;
				$_W['other_setting'] = $setting;
			}
		}
	}
	
	public function doPageBanding() {
		global $_W, $_GPC;
		$op = $_GPC['op'] ? $_GPC['op'] : exit(json_encode(array("status" => 0 , 'msg' => '无上级')));
		if( !isset( $_W['openid'] ) || !$_W['openid'] ) {
			exit(json_encode(array("status" => 0 , 'msg' => '无会员信息')));
		}
		$u_info = pdo_fetch("SELECT * FROM " . tablename("zdaka_user") . " WHERE `openid` = :openid" , array(":openid" => $_W['openid']));
		if($u_info['fuid']){
			exit(json_encode(array("status" => 0 , 'msg' => '已经绑定上级了')));
		}
		$f_info = pdo_fetch("SELECT * FROM " . tablename("zdaka_user") . " WHERE `openid` = :openid" , array(":openid" => $op));
		
		if( !$f_info ) {
			exit(json_encode(array("status" => 0 , 'msg' => '无上级')));
		}
		if( $f_info['id'] == $u_info['id']){
			exit(json_encode(array("status" => 0 , 'msg' => '自己不能邀请自己')));
		}
		$uniacid =  $this->uniacid;
		$openid =  $_W['openid'];
		$fid = intval($_GPC['fid']);
		$data = array(
			'uniacid' => $uniacid,
			'fuid'     => $f_info['id'],
			'cuid'  => $u_info['id'],
			'openid'  => $openid,
			'yaoqing_data'  => date('Y-m-d h:i:s',time()),
			'invitation_endtime' => date('Y-m-d',time()+3600*24*$this->invitation_endtime),
			'invitation_money' => $this->invitation_money,
			'follow_state'  => 0,
		);
		if($this->invitation_money <= 0){
			$data['invitation_status'] = 1;
		}

		//判断该用户是否已经被邀请
		$user = pdo_fetch('SELECT * FROM ' . tablename('zdaka_yaoqing_record') . ' WHERE uniacid ='.$uniacid. ' AND openid ="'.$this->openid.'"');
		if(empty($user)){
			pdo_insert('zdaka_yaoqing_record', $data);
		}
		//else {
		//	pdo_update('zdaka_yaoqing_record',$data,array('id' => $user['id']));
		//}
		pdo_update("zdaka_user" , array(
			"fuid" => $f_info['id'],
			"guid" => $f_info['fuid']
		) , array("openid" => $_W['openid']));
		
		
		exit(json_encode(array("status" => 1 , 'msg' => '绑定成功')));
	}
	
	public function  doPageDKsend($lock=''){
        global $_W,$_GPC;
        $yesterday = date("Y-m-d",strtotime("-1 day"));
        $yesterday1 = date("Y-m-d",strtotime("+1 day"));
        $today = date('Y-m-d',time());
        $time =  date('Y-m-d H:i:s',time());
        $acid=$_W['fans']['uid'];
        $total = pdo_fetchall('SELECT * FROM ' . tablename('zdaka_yajin_record') . ' WHERE uniacid ='.$this->uniacid. ' AND apply_data="' .$today. '" AND yajin_state =1 ');
        $success = pdo_fetchall('SELECT *  FROM ' . tablename('zdaka_sign_record') . ' WHERE uniacid ='.$this->uniacid. ' AND daka_date ="' .$today.'" AND state=1 ');
        $success_count = pdo_fetchcolumn('SELECT SUM(bonus_num) FROM ' . tablename('zdaka_sign_record') . ' WHERE uniacid ='.$this->uniacid. ' AND jibu_status=1 AND daka_date ="' .$today.'"');
        $ptsend=0;
        $ptdemo='';
        $daymoney=pdo_get("zdaka_daymoney_record",array('date'=>$today));
        if($daymoney){
            $ptsend=$daymoney['money']/count($success);
            $ptdemo=',平台赞助：'.$ptsend;
        }
        $total_money = 0;//要分的总钱数
        $success_money = 0;
        $kefen_money=0;//可以分的钱
        foreach ($total as $k=>$v){
            $total_money+=$v['yajin_money'];
        }
        foreach ($success as $k=>$v){
            $success_money+=$v['bonus_num'];
        }
        $kefen_money=($total_money-$success_money)*(100-$this->service)/100;
        $yinli_money=($total_money-$success_money)*$this->service/100;
        if($yinli_money>0){
            $data1 = array(
                'uniacid' => $this->uniacid,
                'money'     => $yinli_money,
                'date' => $today,
                'demo' => $today.'手续费'
            );
            pdo_insert('zdaka_yinli_record', $data1);
        }
        //var_dump($kefen_money);exit;
        $file_name = MODULE_ROOT.'/'.$this->uniacid.'/record/'.$today.'.rlc';
        $file_path = MODULE_ROOT.'/'.$this->uniacid.'/record';
        if (!file_exists($file_path)) {
            load()->func('file');
            mkdirs($file_path);
        }
        file_put_contents($file_name,"奖励金开始发放\n",FILE_APPEND);
        if($kefen_money>=0 && $success!=''){
            if($total_money<=0){
                $jl_money = 0;
            }else {
                $jl_money = ($kefen_money/$success_count);
               // $jl_money = floor($jl_money * 100) / 100;
            }
            foreach($success as $item){
                $jl_money_dan = $jl_money;//单份奖励金
//                $jl_money_count = $jl_money_dan * $item['bonus_num'];
//                $jl_money_count1 = $jl_money_dan * $jl_money_count+$item['bonus_num'];
                //更改余额
                if(strtotime($item['huikuan_date'])<=strtotime(date('Y-m-d',time()))){
                    $jl_money_count = $jl_money_dan * $item['bonus_num']+$item['bonus_num']+$ptsend;
                    $jl_money_count = floor($jl_money_count * 100) / 100;
                    pdo_update('zdaka_user',array('money +='=>$jl_money_count),array('uniacid' => $item['uniacid'],'openid' => $item['openid']));
                    pdo_update('zdaka_yajin_record',array('yajin_state' => 2,'demo'=>'已经完成挑战'),array('id' => $item['yid']));
                    $demo=$today.'奖励金和当期挑战金'.$ptdemo;
                }else{
                    $jl_money_count = $jl_money_dan * $item['bonus_num']+$ptsend;
                    $jl_money_count = floor($jl_money_count * 100) / 100;
                    pdo_update('zdaka_user',array('money +='=>$jl_money_count),array('uniacid' => $item['uniacid'],'openid' => $item['openid']));
                    pdo_update('zdaka_yajin_record',array('apply_data' => $yesterday1,'demo'=>'打卡成功，押金继续'),array('id' => $item['yid']));
                    $demo= $today.'获得奖励金'.$ptdemo;
                }
                //更改状态
                pdo_update('zdaka_sign_record',array('state' => 2,'jibu_status'=>0),array('id' => $item['id']));
                //更改打卡奖励总记录
                pdo_update('zdaka_total_record',array('user_total_money +=' => $jl_money_count),array('uniacid' => $item['uniacid'],'openid' => $item['openid']));
                //插入分钱记录
                $data = array(
                    'uniacid' => $item['uniacid'],
                    'uid'     => $item['uid'],
                    'openid'     => $item['openid'],
                    'nickname'  => $item['nickname'],
                    'headimgurl'  => $item['headimgurl'],
                    'grant_data' => $time,
                    'grant_date' => $today,
                    'grant_money' => $jl_money_count,
                    'bonus_num' => $item['bonus_num'],
                  	'num' => $item['num'],
                    'demo' => $demo
                );
                pdo_insert('zdaka_grant_record', $data);
                //记录打卡成功人的uid
                file_put_contents($file_name,"用户".$item['uid']."单份".$jl_money_dan."元 份数".$item['bonus_num']." 总额".$jl_money_count."奖励金已发放\n",FILE_APPEND);
            }
        }else{
            foreach($success as $item){

//                $jl_money_count = $jl_money_dan * $item['bonus_num'];
//                $jl_money_count1 = $jl_money_dan * $jl_money_count+$item['bonus_num'];
                //更改余额
                if(strtotime($item['huikuan_date'])<=strtotime(date('Y-m-d',time()))){
                    pdo_update('zdaka_user',array('money +='=>$item['bonus_num']+$ptsend),array('uniacid' => $item['uniacid'],'openid' => $item['openid']));
                    pdo_update('zdaka_yajin_record',array('yajin_state' => 2,'demo'=>'已经完成挑战'),array('id' => $item['yid']));
                    $demo=$today.'奖励金和当期挑战金'.$ptdemo;
                }else{
                    pdo_update('zdaka_yajin_record',array('apply_data' => $yesterday1,'demo'=>'打卡成功，押金继续'),array('id' => $item['yid']));
                    $demo=$today. '获得奖励金'.$ptdemo;
                }
                //更改状态
                pdo_update('zdaka_sign_record',array('state' => 2,'jibu_status'=>0),array('id' => $item['id']));
                //更改打卡奖励总记录
                pdo_update('zdaka_total_record',array('user_total_money +=' => 0),array('uniacid' => $item['uniacid'],'openid' => $item['openid']));
                //插入分钱记录
                $data = array(
                    'uniacid' => $item['uniacid'],
                    'uid'     => $item['uid'],
                    'openid'     => $item['openid'],
                    'nickname'  => $item['nickname'],
                    'headimgurl'  => $item['headimgurl'],
                    'grant_data' => $time,
                    'grant_date' => $today,
                    'grant_money' => 0,
                  'num' => $item['num'],
                    'bonus_num' => $item['bonus_num'],
                    'demo' => $demo
                );
                pdo_insert('zdaka_grant_record', $data);
                //记录打卡成功人的uid
                file_put_contents($file_name,"用户".$item['uid']."单份0元 份数".$item['bonus_num']." 总额0奖励金已发放\n",FILE_APPEND);
            }
        }
        //修改打卡失败用户的押金状态
        pdo_update('zdaka_yajin_record',array('yajin_state' => 0,'demo'=>'未打卡','Invaliddate' => $today,'updata_date'=>$today,'bonus_num'=>0),array('uniacid' => $this->uniacid,'yajin_state' => 1,'daka_date !='=>$today,'updata_date'=>'0000-00-00','apply_data'=>$today,'yajin_data <'=>date('Y-m-d H:i:s',$this->today_end)));
        file_put_contents($file_name,"奖励金发放结束\n",FILE_APPEND);
		if(!empty($lock)){
			//执行完成解锁
			flock($lock,LOCK_UN);		
		}		
    }
	
	public function  doPageYqsend(){
		global $_W, $_GPC;
		$ordday = date("Y-m-d",time());
		$success = pdo_fetchall('SELECT *  FROM ' . tablename('zdaka_yaoqing_record') . ' WHERE uniacid ='.$this->uniacid. ' AND invitation_status=0 AND invitation_endtime <='."'" .$ordday."'");
		
		foreach($success as $key=>$val){
			$user=pdo_get('zdaka_user',array('id'=>$val['fuid']));
			if(pdo_update('zdaka_user',array('money +='=>$val['invitation_money']),array('uniacid' => $val['uniacid'],'openid' => $user['openid']))){
				pdo_update('zdaka_yaoqing_record',array('invitation_status'=>1,'invitation_time'=>$ordday),array('uniacid' => $val['uniacid'],'id' => $val['id']));	
			}
		}
		
	}
	
	public function doPageDecrypt(){
		global $_W, $_GPC;
		
		$res=pdo_get('zdaka_config',array('uniacid'=>$_W['uniacid']));
		$res['settings'] = json_decode($res['settings'],true);
		$appid=$res['settings']['appid'];
		$sessionKey = $_GPC['session'];
		$encryptedData = $_GPC['encryptedData'];
		$iv = $_GPC['iv'];
		$pc = new WXBizDataCrypt($appid, $sessionKey);
		$errCode = $pc->decryptData($encryptedData, $iv, $data );

		if ($errCode == 0) {
			print($data . "\n");
		} else {
			print($errCode . "\n");
		}
	}
	
	
}


